package cn.edu.nks.dormitory.admin.stumanage.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import cn.edu.nks.dormitory.admin.stumanage.db.IDBService;
import cn.edu.nks.dormitory.admin.stumanage.dbimpl.DBService;
import cn.edu.nks.dormitory.model.StudentInfo;
import cn.edu.nks.util.DateTimeUtil;

public class ShowStudentsInfoAction extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(ShowStudentsInfoAction.class);
	IDBService idbService = new DBService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/jsons;charset=utf-8");
		String page = req.getParameter("page");
		String rows = req.getParameter("rows");
		int count = idbService.getCount();
		List<StudentInfo> items = idbService.getStudents(Integer.valueOf(page),Integer.valueOf(rows));
		JSONArray arry = new JSONArray();
		for (StudentInfo studentInfo : items) {
			JSONObject jobj = new JSONObject();
			jobj.put("studentId", studentInfo.getStudentId());
			jobj.put("classId", studentInfo.getClassId());
			jobj.put("grade", studentInfo.getGrade());
			jobj.put("realName", studentInfo.getRealName());
			jobj.put("telephone", studentInfo.getTelephone());
			jobj.put("email", studentInfo.getEmail());
			jobj.put("sex", studentInfo.getSex());
			jobj.put("birthday", DateTimeUtil.toDateString(studentInfo.getBirthday()));
			jobj.put("height", studentInfo.getHeight());
			jobj.put("weight", studentInfo.getWeight());
			jobj.put("region", studentInfo.getRegion());
			jobj.put("addr", studentInfo.getAddr());
			jobj.put("jsons", studentInfo.getJsons());
			arry.add(jobj);
		}
		logger.warn(String.format("load stus %s", items.toString()));
		JSONObject obj = new JSONObject();
		obj.put("total", count);
		obj.put("rows", arry);
		PrintWriter out = resp.getWriter();
		out.write(obj.toString());
	}
}
